package com.example.demo.rocketMQ.mqtt;

import org.apache.rocketmq.mqtt.common.util.HmacSHA1Util;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MqttProducer {
    public static void main(String[] args) throws InterruptedException, MqttException, NoSuchAlgorithmException, InvalidKeyException {
        MemoryPersistence memoryPersistence = new MemoryPersistence();//用于在内存中保存未发送的消息，防止消息丢失。
        String brokerUrl = "tcp://" + System.getenv("host") + ":1883";//MQTT Broker 的地址 URL
        String firstTopic = System.getenv("topic");//从环境变量中读取主机地址
        String sendClientId = "send01";//定义客户端 ID，用于标识当前 MQTT 客户端。
        MqttConnectOptions mqttConnectOptions = buildMqttConnectOptions(sendClientId);//创建 MQTT 连接配置选项对象
        MqttClient mqttClient = new MqttClient(brokerUrl, sendClientId, memoryPersistence);//创建 MQTT 连接配置选项对象
        mqttClient.setTimeToWait(5000L);//设置客户端等待响应的最大时间为 5 秒
        mqttClient.setCallback(new MqttCallbackExtended() {//设置 MQTT 客户端的回调函数，用于处理连接完成、消息到达等事件。
            @Override
            public void connectComplete(boolean reconnect, String serverURI) {//当客户端成功连接到 Broker 时触发此方法
                System.out.println(sendClientId + " connect success to " + serverURI);
            }

            @Override
            public void connectionLost(Throwable throwable) {//当客户端与 Broker 断开连接时触发此方法
                throwable.printStackTrace();
            }

            @Override
            public void messageArrived(String topic, MqttMessage mqttMessage) {//当客户端接收到订阅主题的消息时触发此方法
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {//当消息成功发送到 Broker 后触发此方法
            }
        });
        try {
            mqttClient.connect(mqttConnectOptions);//尝试连接到 MQTT Broker，并捕获连接过程中可能出现的异常。
        } catch (Exception e) {
            e.printStackTrace();
        }
        long interval = 1000;//定义两次消息发送之间的间隔时间
        for (int i = 0; i < 1000; i++) {
            String msg = "r1_" + System.currentTimeMillis() + "_" + i;
            MqttMessage message = new MqttMessage(msg.getBytes(StandardCharsets.UTF_8));
            message.setQos(1);//设置消息的服务质量等级为 QoS 1（至少送达一次）
            String mqttSendTopic = firstTopic + "/r1";
            mqttClient.publish(mqttSendTopic, message);//向指定主题发布消息
            System.out.println(now() + "send: " + mqttSendTopic + ", " + msg);
            Thread.sleep(interval);

            mqttSendTopic = firstTopic + "/r/wc";
            msg = "wc_" + System.currentTimeMillis() + "_" + i;
            MqttMessage messageWild = new MqttMessage(msg.getBytes(StandardCharsets.UTF_8));
            messageWild.setQos(1);
            mqttClient.publish(mqttSendTopic, messageWild);
            System.out.println(now() + "send: " + mqttSendTopic + ", " + msg);
            Thread.sleep(interval);

            mqttSendTopic = firstTopic + "/r2";
            msg = "msgQ2_" + System.currentTimeMillis() + "_" + i;
            message = new MqttMessage(msg.getBytes(StandardCharsets.UTF_8));
            message.setQos(2);//设置消息的服务质量等级为 QoS 2（确保送达一次且仅一次）
            mqttClient.publish(mqttSendTopic, message);
            System.out.println(now() + "send: " + mqttSendTopic + ", " + msg);
            Thread.sleep(interval);
        }
    }

    private static MqttConnectOptions buildMqttConnectOptions(String clientId) throws NoSuchAlgorithmException, InvalidKeyException {
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(true);//设置客户端为“干净会话”模式，即每次连接都清除之前的会话状态。
        connOpts.setKeepAliveInterval(60);//设置客户端与 Broker 保持心跳的时间间隔（单位：秒）
        connOpts.setAutomaticReconnect(true);//启用自动重连功能，当连接断开时自动尝试重新连接
        connOpts.setMaxInflight(10000);//设置客户端同时允许的最大未确认消息数量
        connOpts.setUserName(System.getenv("username"));//从环境变量中读取用户名，用于认证。
        connOpts.setPassword(HmacSHA1Util.macSignature(clientId, System.getenv("password")).toCharArray());//从环境变量中读取密码，并使用 HmacSHA1 算法生成签名作为密码
        return connOpts;
    }

    private static String now() {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        return sf.format(new Date()) + "\t";
    }
}
